<template>
  <div>
    <van-tabbar v-model="tabIndex">
      <van-tabbar-item
        v-for="tabbar in tabbars"
        :key="tabbar.name"
        :to="tabbar.path"
        :icon="tabbar.meta.icon"
      >
        {{tabbar.meta.title}}
        <span class="badge" v-if="tabbar.name === 'Cart'">{{totalCount | over99}}</span>
      </van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import routes from '@/router/routers'
export default {
  name: 'Tabbar',
  data () {
    return {
      tabIndex: 0
    }
  },
  computed: {
    ...mapGetters(['totalCount']),
    tabbars () {
      return routes.filter(route => route.meta.isTabbar)
    }
  },
  created () {
    this.tabbars.forEach((tab, index) => {
      // tabInde 修改为当前路由所在的索引，否则一刷新就回到默认为0 到首页了
      // 从tabbar 里去根据路由path来匹配修改tabIndex 的默认值
      if (tab.path === '/' + this.$route.path.split('/')[1]) {
        this.tabIndex = index
      }
    })
  }
}
</script>

<style>
.van-tabbar-item {
  position: relative;
}
.badge {
  position: absolute;
  padding: 1px 4px;
  border-radius: 10px;
  left: 55px;
  top: 3px;
  background-color: red;
  color: #fff;
}
</style>
